<?php

$data['authors'] = array();
$data['errors'] = array();

if (isset($_POST['author'])) {
    $author_name = trim($_POST['author']);
    if (mb_strlen($author_name) < 3) {
        $data['errors'][] = 'Името на автора трябва да е дълго поне 3 символа';
    } else {
        $author_name_esc = mysqli_real_escape_string($connection, $author_name);
        $sql = 'SELECT author_name FROM authors 
                WHERE author_name="' . $author_name_esc . '"';
        $result = mysqli_query($connection, $sql);
        if (mysqli_num_rows($result) == 0) {
            $sql = 'INSERT INTO authors (author_id, author_name)
                    VALUES (NULL, "' . $author_name_esc . '");';
            mysqli_query($connection, $sql);
            header('Location: index.php?p=new-author');
            exit();
        } else {
            $data['errors'][] = 'Този автор вече съществува';
        }
    }
}

$query = mysqli_query($connection, 'SELECT * FROM authors ORDER BY author_name ASC');
$author = array();
while ($row = mysqli_fetch_assoc($query)) {
    $author['id'] = $row['author_id'];
    $author['name'] = $row['author_name'];
    $data['authors'][] = $author;
}

$data['title'] = 'Нов автор';
render($data, 'templates/new-author_public.php');